﻿using System;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;

namespace Bpms.Data
{
    public class SqlServerProvider : IDbProvider
    {
        public DbProviderFactory Instance()
        {
            return SqlClientFactory.Instance;
        }

        public string GetLastIdSql()
        {
            return "SELECT SCOPE_IDENTITY()";
        }

        public DbParameter MakeParam(string ParamName, DbType DbType, Int32 Size)
        {
            SqlParameter param;

            if (Size > 0)
                param = new SqlParameter(ParamName, (SqlDbType)DbType, Size);
            else
                param = new SqlParameter(ParamName, (SqlDbType)DbType);

            return param;
        }

        public int GetId(string fieldName, string tableName, string condition)
        {
            string sqlStr = "SELECT MAX(" + fieldName + ") AS id FROM  " + tableName + " ";
            if (string.IsNullOrEmpty(condition))
            {
                sqlStr += " WHERE " + condition + "";
            }

            try
            {
                return Bpms.Common.Utility.ToInt(DbHelper.ExecuteScalar(CommandType.Text, sqlStr, null)) + 1;
            }
            catch
            {
                return 1;
            }
        }
    }
}
